<?php

class ClassQiniu extends ClassOption {

    private $aConfig;

    public function __construct($hvConfig) {
        parent::__construct($hvConfig);
        $this->aConfig = $hvConfig['config'];
        $this->SetConfig($this->GetStorageConfig());
    }

    private function SetConfig($aConfig) {
        $this->aConfig['accessKey'] = $aConfig['accessKey'];
        $this->aConfig['secretKey'] = $aConfig['secretKey'];
        $this->aConfig['domain'] = $aConfig['domain'];
        $this->aConfig['bucket'] = $aConfig['bucket'];
        $this->aConfig['upHost'] = $aConfig['upHost'];
    }

    public function MakeUploadToken($action, $filename, $user_id) {
        $base64_urlSafeEncode = function ($data) {
            $find = array('+', '/');
            $replace = array('-', '_');
            return str_replace($find, $replace, base64_encode($data));
        };
        $AccessKey = $this->aConfig['accessKey'];
        $SecretKey = $this->aConfig['secretKey'];
        $putPolicy = array();
        $putPolicy['scope'] = $this->aConfig['bucket'] . ':' . $filename;
        $putPolicy['deadline'] = time() + 600;
        $putPolicy['callbackBody'] = 'qiniu_imageInfo=$(imageInfo)&qiniu_bucket=$(bucket)&qiniu_key=$(key)';
        $putPolicy['callbackBody'] .= '&user_id=' . $user_id;
        $putPolicy['callbackUrl'] = $this->aConfig['callbackUrlPre'] . $action . '?test=1';
        $encodedData = $base64_urlSafeEncode(json_encode($putPolicy));
        $hmac = hash_hmac('sha1', $encodedData, $SecretKey, true);
        return $AccessKey . ':' . $base64_urlSafeEncode($hmac) . ':' . $encodedData;
    }

    public function GetUploadForm($action, $filename, $user_id) {
        $fromdata = array();
        $fromdata['key'] = $filename;
        $fromdata['token'] = $this->MakeUploadToken($action, $filename, $user_id);
        $upload_form = array();
        $upload_form['method'] = 'post';
        $upload_form['posttype'] = 'formdata';
        $upload_form['url'] = 'https://' . $this->aConfig['upHost'] . '/';
        $upload_form['formdata'] = $fromdata;
        $upload_form['file_field_name'] = 'file';
        $upload_form['headers'] = array();
        $upload_form['headers']['Content-Type'] = 'multipart/form-data';
        return $upload_form;
    }

    public function CheckAuthorization($sRawUrl, $hAuthorization, $sRawContent) {
        $aAuth = explode(':', $hAuthorization);
        if (count($aAuth) < 2) {
            return FALSE;
        }
        $base64_urlSafeEncode = function ($data) {
            $find = array('+', '/');
            $replace = array('-', '_');
            return str_replace($find, $replace, base64_encode($data));
        };
        // $sRawUrl == $_SERVER['REQUEST_URI']
        $data = $sRawUrl . "\n" . $sRawContent;
        $hmac_base64 = $base64_urlSafeEncode(hash_hmac('sha1', $data, $this->aConfig['secretKey'], true));
        return $aAuth[1] === $hmac_base64;
    }

    public function GetImageUrl($qiniu_key) {
        return '//' . $this->aConfig['domain'] . '/' . $qiniu_key;
    }

    public function putAvatarToRow(&$mRow) {
        if (!empty($mRow['avatar_file_key'])) {
            $mRow['headimgurl'] = $this->ReplaceStorageUrl($mRow['avatar_file_key']);
            $mRow['headimgurl'] .= '~avatar128.jpg?updated=' . $mRow['avatar_updated'];
            unset($mRow['avatar_file_key']);
            unset($mRow['avatar_updated']);
            return;
        }
        $mRow['headimgurl'] = str_replace('http://', '//', $mRow['headimgurl']);
    }


    public function getAvatarUrl($db_dreamss, $user_id) {
        $mWhere = array('user_id' => $user_id);
        $user_avatar = $db_dreamss->sql()->table('user_avatar')->where($mWhere)->field('file_key,updated')->find();
        if ($user_avatar) {
            $headimgurl = $this->ReplaceStorageUrl($user_avatar['file_key']);
            $headimgurl .= '~avatar128.jpg?updated=' . $user_avatar['updated'];
            return $headimgurl;
        }
        $user_wxoauth = $db_dreamss->sql()->table('user_wxoauth')->where($mWhere)->field('headimgurl')->find();
        $headimgurl = $user_wxoauth['headimgurl'];
        $headimgurl = str_replace('http://', '//', $headimgurl);
        return $headimgurl;
    }

}
